<template>
  <draggable
    v-model="data.list"
    v-bind="{
      group: 'people',
      ghostClass: 'ghost',
      animation: 200,
      handle: '.drag-widget',
    }"
    @end="handleMoveEnd"
    @add="handleWidgetAdd"
  >
    <transition-group name="fade" tag="div" class="widget-form-list">
      <template v-for="(element, index) in data.list">
        <template v-if="element.type === 'grid'">
          <div v-if="element && element.key" :key="element.key"
            class="widget-col widget-view"
            :class="{ active: selectWidget.key == element.key }"
            @click.stop="handleSelectWidget(index)"
          >
            <a-row
              type="flex"
              :gutter="element.options.gutter > 0 ? element.options.gutter : 0"
              :justify="element.options.justify"
              :align="element.options.align"
            >
              <a-col v-for="(col, colIndex) in element.columns" :key="colIndex" :span="col.span ? col.span : 0">
                <draggable
                  v-model="col.list"
                  :no-transition-on-drag="true"
                  v-bind="{
                    group: 'people',
                    ghostClass: 'ghost',
                    animation: 200,
                    handle: '.drag-widget',
                  }"
                  @end="handleMoveEnd"
                  @add="handleWidgetColAdd($event, element, colIndex)"
                >
                  <transition-group name="fade" tag="div" class="widget-col-list">
                    <template v-for="(el, i) in col.list">
                      <widget-form-item
                        v-if="el.key"
                        :key="el.key"
                        :element="el"
                        :select.sync="selectWidget"
                        :widgetIndex="i"
                        :data="col"
                      />
                    </template>
                  </transition-group>
                </draggable>
              </a-col>
              <div class="widget-view-action" v-if="selectWidget.key == element.key">
                <i
                  class="iconfont icon-trash"
                  @click.stop="handleWidgetDelete(index)"
                ></i>
              </div>
              <div class="widget-view-drag" v-if="selectWidget.key == element.key">
                <i class="iconfont icon-drag drag-widget"></i>
              </div>
            </a-row>
          </div>
        </template>
        <template v-else>
          <widget-form-item
            v-if="element && element.key"
            :key="element.key"
            :element="element"
            :select.sync="selectWidget"
            :widget-index="index"
            :data="data"
          />
        </template>
      </template>
    </transition-group>
  </draggable>
</template>

<script>
import Draggable from "vuedraggable";
import WidgetFormItem from "./WidgetFormItem.vue";
export default {
  name: 'WidgetForm',
  components: {
    Draggable,
    WidgetFormItem,
  },
  props: ["data", "select"],
  data() {
    return {
      selectWidget: this.select,
    };
  },
  mounted() {
    document.body.ondrop = function (event) {
      let isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
      if (isFirefox) {
        event.preventDefault();
        event.stopPropagation();
      }
    };
  },
  watch: {
    selectWidget: {
      handler(val) {
        this.$emit("update:select", val);
      },
      deep: true,
    },
    select(val) {
      this.selectWidget = val;
    },
  },
  methods: {
    handleWidgetAdd(payload) {
      console.log("handleWidgetAdd", payload);
      const { newIndex } = payload;
      const key =
        Date.parse(new Date().toString()) +
        "_" +
        Math.ceil(Math.random() * 99999);
      this.$set(this.data.list, newIndex, {
        ...this.data.list[newIndex],
        options: {
          ...this.data.list[newIndex].options,
          remoteFunc: "func_" + key,
        },
        key,
        // 绑定键值
        model: this.data.list[newIndex].type + "_" + key,
        rules: [],
      });
      if ( ['radio', 'checkbox'].includes(this.data.list[newIndex].type)) {
        this.$set(this.data.list, newIndex, {
          ...this.data.list[newIndex],
          options: {
            ...this.data.list[newIndex].options,
            options: this.data.list[newIndex].options.options.map((item) => ({...item})),
          },
        })
      }
      if (this.data.list[newIndex].type === 'grid') {
        this.$set(this.data.list, newIndex, {
          ...this.data.list[newIndex],
          columns: this.data.list[newIndex].columns.map((item) => ({...item}))
        })
      }
      this.selectWidget = this.data.list[newIndex];
    },
    handleWidgetColAdd($event, row, colIndex) {
      console.log("coladd", $event, row, colIndex);
      const item = $event.item;
      const newIndex = $event.newIndex;
      console.log('item',item);
      const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      this.$set(row.columns[colIndex].list, newIndex, {
        ...row.columns[colIndex].list[newIndex],
        options: {
          ...row.columns[colIndex].list[newIndex].options,
          remoteFunc: 'func_' + key
        },
        model: row.columns[colIndex].list[newIndex].type + '_' + key,
        rules: [],
        key,
      })
      this.selectWidget = row.columns[colIndex].list[newIndex]
    },
    handleMoveEnd(payload) {
      console.log("MoveEnd", payload);
    },
    handleSelectWidget(index) {
      this.selectWidget = this.data.list[index];
    },
    handleWidgetDelete(index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.selectWidget = {};
        } else {
          this.selectWidget = this.data.list[index - 1];
        }
      } else {
        this.selectWidget = this.data.list[index + 1];
      }
      this.$nextTick(() => {
        this.data.list.splice(index, 1);
      });
    },
  },
};
</script>

<style></style>
